<?php
/**
 * 性能统计基础类库
 *
 * @version 1.1 2010-08-03
 * @author Ivan<hanwei@leju.sina.com.cn>
 */
$profiler = new lib_base_profiler();
class lib_base_profiler
{
	private $_warnning_time	= 3;	//默认超时时间
	private $_last_time		= 0;	//上个标记点时间
	private $_memory_used	= 0;	//所用内存
	private $_total_time	= 0;	//总时间
	private $_total_memory	= 0;	//总时间
	private $_marks	= array();
	private $_stop	= false;

	public function __construct()
	{
		$this->_last_time = microtime(TRUE);
		$this->_memory_used = memory_get_usage();
	}

	/**
	 * 添加标记
	 *
	 * @param String $name 标记名 ，如果不填默认为文件名+行号
	 */
	public function add_mark($name=null)
	{
		if ($this->_stop)
		{
			return false;
		}
		if (is_null($name))
		{
			$backtrace = debug_backtrace();
			$name = $backtrace[0]['file'].':'.$backtrace[0]['line'];
		}
		$mark = array('mark' =>$name);
		$mark['time'] = microtime(TRUE)-$this->_last_time;
		$this->_last_time = microtime(TRUE);
		//以KB为单位显示内存使用大小
		$mark['memory'] = ceil((memory_get_usage()-$this->_memory_used) / 1024);
		$this->_memory_used = memory_get_usage();
		$this->_total_time += $mark['time'];
		$this->_total_memory += $mark['memory'];
		$this->_marks[] = $mark;
	}

	/**
	 * 停止统计
	 *
	 */
	public function stop()
	{
		$this->add_mark('stop');
		$this->_stop = true;
	}

	/**
	 * 查看结果
	 *
	 * @param String $format text|html   格式：目前支持纯文本和html两种格式 默认按html格式显示
	 */
	public function show_result($format='html')
	{
		//如果没有显式调用stop方法，则用当前时间作为停止时间
		if (!$this->_stop)
		{
			$this->stop();
		}
		if ('html' == $format)
		{
			echo "<pre> \r\n";
		}
		foreach ($this->_marks as $mark => $value) {
			echo "mark:",$value['mark'],"\t time:",$value['time'],"\t memory:",$value['memory'],"KB \r\n";
		}
		echo "Total:",$this->_total_time,"	Memory:",$this->_total_memory,"KB \r\n";
		if ('html' == $format)
		{
			echo '</pre>';
		}
	}

	/**
	 * 设置超时时间，默认为3秒
	 *
	 * @param Integer $time 大于等于0的整数
	 */
	public function set_warnning_time($time)
	{
		if (is_int($time) && $time >= 0)
			$this->_warnning_time = $time;
		return TRUE;
	}

	public function __destruct()
	{
		//超时时间为0，不进行限制
		if ($this->_warnning_time > 0 && $this->_total_time > $this->_warnning_time)
		{
			//@todo超过警告时间 记录超时日志
		}
	}
}
?>